package cn.edu.sctu.sctu_lysd.view.act;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.text.ParseException;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.alipay.PayActivity;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.ParcelData;
import cn.edu.sctu.sctu_lysd.biz.MyAcceptBiz;
import cn.edu.sctu.sctu_lysd.biz.OrderDetailedMessageBiz;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.cofig.Status;
import cn.edu.sctu.sctu_lysd.databinding.ActivityMyAcceptOrdersDetailedBinding;
import cn.edu.sctu.sctu_lysd.databinding.ActivityMyOrdersDetailedBinding;
import cn.edu.sctu.sctu_lysd.my_view.CustomDialog;
import cn.edu.sctu.sctu_lysd.presenter.MyAcceptPresenter;
import cn.edu.sctu.sctu_lysd.presenter.OrderDetailedPresenter;
import cn.edu.sctu.sctu_lysd.utils.DateUtils;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;
import io.rong.imkit.RongIM;

/**
 * Created by wangfuxin on 2017-04-14.
 */

public class MyAcceptOrderDetailedAct extends BaseActivity implements MyAcceptBiz.View {

    public final static String INTENT_ID_TAG = "parcelId";
    private MyAcceptBiz.Presenter mPresenter;
    private ActivityMyAcceptOrdersDetailedBinding mBinding;

    private long parcelId = 0;

    private static final int INTENT_SCAN_REQUEST_CODE = 8888;

    private ProgressUtil progressUtil;
    private ProgressDialog progressDialog;


    // 要申请的权限
    private String[] permissions = {Manifest.permission.CAMERA};

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_my_accept_orders_detailed;
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityMyAcceptOrdersDetailedBinding) bind;

        initPresenter(new MyAcceptPresenter(this, this));

        progressUtil = ProgressUtil.getInstance(this);

        getIntentData();

        mPresenter.getOrder(parcelId);


    }

    private void contactCreator(long creatorId) {
        //启动会话界面
        if (RongIM.getInstance() != null)
            RongIM.getInstance().startPrivateChat(MyAcceptOrderDetailedAct.this,
                    String.valueOf(creatorId),
                    SharePreferenceUtils.getInstance(MyAcceptOrderDetailedAct.this).getString(CacheKeyConfig.CACHE_USER_NICKNAME));
    }


    private void getIntentData() {

        Bundle bundle = getIntent().getExtras();

        parcelId = bundle.getLong(INTENT_ID_TAG);


    }

    private void initScan() {

        startActivityForResult(new Intent(MyAcceptOrderDetailedAct.this, CaptureActivity.class), INTENT_SCAN_REQUEST_CODE);

    }


    @Override
    public void finishParcelSuccess() {

        progressUtil.dismiss(progressDialog);

        ProgressUtil.showAlertDialog("订单完成", "恭喜您完成任务啦！", this, new ProgressUtil.AlertDialogCallBack() {
            @Override
            public void submit() {

                JumpUtils.jumpActivity(MyAcceptOrderDetailedAct.this,IndexActivity.class);
            }

            @Override
            public void cancel() {
                JumpUtils.jumpActivity(MyAcceptOrderDetailedAct.this,IndexActivity.class);
            }
        });

    }

    @Override
    public void finishParcelFailed(int message) {

        progressUtil.dismiss(progressDialog);

        switch (message) {

            case MyAcceptPresenter.ERROR_MISMATCH://扫码人与包裹是不匹配

                Toast.makeText(this,"您不是这个包裹的送货人",Toast.LENGTH_LONG).show();

                break;
            case MyAcceptPresenter.ERROR_REPEAT:

                Toast.makeText(this,"您已经扫描过了",Toast.LENGTH_LONG).show();

                break;

            default:
                Toast.makeText(this,"网络错误",Toast.LENGTH_LONG).show();

                break;
        }

    }


    public void parcelDetailedBack(View view) {

        finish();

    }

    @Override
    public void initPresenter(MyAcceptBiz.Presenter presenter) {

        this.mPresenter = presenter;

        mPresenter.start();

    }

    @Override
    public void getOrderSuccess(final ParcelData data) {

        /**
         * 扫码完成
         */
        mBinding.scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(MyAcceptOrderDetailedAct.this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(MyAcceptOrderDetailedAct.this, permissions, 321);
                } else {
                    initScan();
                }


            }
        });

        /**
         * 练习包裹主人
         */
        mBinding.contactCreator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                contactCreator(data.getCreator());

            }
        });

        try {

            switch (data.getIsSuccess()) {

                case Status.PARCEL_IS_NOT_SUCCESS://包裹送达

                    mBinding.parcelStatus.setText("包裹未送达");

                    break;
                case Status.PARCEL_IS_SUCCESS://包裹未送达

                    mBinding.parcelStatus.setText("包裹已送达");

                    mBinding.contactCreator.setText("包裹已送达");
                    mBinding.contactCreator.setClickable(false);
                    mBinding.contactCreator.setBackgroundColor(Color.parseColor("#FF434242"));

                    break;
                case Status.PARCEL_IS_SUCCESS_://包裹未送达

                    mBinding.parcelStatus.setText("包裹已送达");

                    mBinding.contactCreator.setText("包裹已送达");
                    mBinding.contactCreator.setClickable(false);
                    mBinding.contactCreator.setBackgroundColor(Color.parseColor("#FF434242"));

                    break;

                default:
                    break;

            }

            mBinding.startPlaceTxt.setText(data.getOrigin());
            mBinding.endPlaceTxt.setText(data.getDestination());

            mBinding.startTimeTxt.setText(DateUtils.dateToStr(data.getStartTime(), DateUtils.DATE_SDF));
            mBinding.endTimeTxt.setText(DateUtils.dateToStr(data.getEndTime(), DateUtils.DATE_SDF));

            mBinding.nameAndPhoneTxt.setText(data.getReceiverName() + " : " + data.getReceiverPhone());
            mBinding.addresseePlaceTxt.setText(data.getDestination());

            mBinding.goodsNameTxt.setText(data.getName());
            mBinding.goodsWeightTxt.setText(data.getWeight() + "kg");
            mBinding.goodsDescriptionTxt.setText(data.getDescription());

            mBinding.price.setText(data.getOrderAmount() + "元");

            mBinding.goodsImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShowImgAct.intentThis(MyAcceptOrderDetailedAct.this,data.getParcelPhotoUrl());
                }
            });

            Picasso.with(this).load(data.getParcelPhotoUrl()).into(mBinding.goodsImg);


        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void getOrderFailed() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK && requestCode == INTENT_SCAN_REQUEST_CODE) {

            String result = data.getExtras().getString("result");

            L.e("scan result", result);

            progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL,false,"请稍后...");

            mPresenter.finishParcel(parcelId);

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }


    }
}
